﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System.Text;
using System.Collections.Generic;

using Twipler.App.Machine;

namespace Twipler.App.Render.Tree
{
    public class IfItem : AbstractItem
    {
        private List<Instruction> _condition;
        private AbstractItem _ifBlock;
        private AbstractItem _elseBlock;

        public override List<AbstractItem> Children
        {
            get 
            {
                return _elseBlock == null ? new List<AbstractItem> { _ifBlock } : new List<AbstractItem> { _ifBlock, _elseBlock};
            }
        }

        public static IfItem Create(List<Instruction> condition, AbstractItem ifBlock, AbstractItem elseBlock)
        {
            IfItem item = new IfItem();

            item._condition = condition;
            item._ifBlock = ifBlock;
            item._elseBlock = elseBlock;

            return item;
        }
        
        public override void Render(StringBuilder html, App.Machine.Environment environment)
        {
            object var = environment.Execute(_condition);

            if ((var != null) && (var is bool) && ((bool)var))
            {
                _ifBlock.Render(html, environment);
            }
            else if (_elseBlock != null)
            {
                _elseBlock.Render(html, environment);
            }
        }
    }
}
